package cn.edu.gzmtu.service.impl;

import cn.edu.gzmtu.dao.IUserDao;
import cn.edu.gzmtu.domain.Role;
import cn.edu.gzmtu.domain.UserInfo;
import cn.edu.gzmtu.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 用户模块service层实现类
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;

    // 密码加密需要使用到的类
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = null;
        try {
            userInfo = userDao.findByUsername(username);

        } catch (Exception e) {
            e.printStackTrace();
        }

        // 把自己的对象封装成UserDetails
        // public class User implements UserDetails, CredentialsContainer {}
        // User("用户名"， "密码"，"角色") // 简略构造
        // User("用户名"， "密码"，"账户是否可用"，"是否锁定"，ture， true，"角色") // 详细构造

        // User user = new User(userInfo.getUsername(), "{noop}" + userInfo.getPassword(), getAuthority(userInfo.getRoles()));

        boolean enabled = userInfo.getStatus() == 0 ? false : true; // 判断用户是否开启

        // User user = new User(userInfo.getUsername(), "{noop}" + userInfo.getPassword(), enabled, true, true, true, getAuthority(userInfo.getRoles()));

        User user = new User(userInfo.getUsername(), userInfo.getPassword(), enabled, true, true, true, getAuthority(userInfo.getRoles()));

        return user;
    }


    /**
     * 作用：返回一个List集合，集合中装入的是角色描述
     *
     * @return
     */
    private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        for (Role role : roles) {

            list.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        return list;
    }

    /**
     * 查询所有用户
     * @return
     */
    @Override
    public List<UserInfo> findAll() throws Exception {
        return userDao.findAll();
    }

    /**
     * 添加用户
     * @param userInfo
     * @throws Exception
     */
    @Override
    public void save(UserInfo userInfo) throws Exception {

        // 对密码进行加密操作
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));

        userDao.save(userInfo);
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public UserInfo findById(String id) throws Exception {
        return userDao.findById(id);
    }

    /**
     * 查询用户没有的角色
     * @param userId
     * @return
     */
    @Override
    public List<Role> findUserOtherRoles(String userId) throws Exception {
        return userDao.findUserOtherRoles(userId);
    }

    /**
     * 为用户添加角色
     * @param userId
     * @param roleIds
     * @throws Exception
     */
    @Override
    public void addRoleToUser(String userId, String[] roleIds) throws Exception {
        for (String roleId : roleIds) {
            userDao.addRoleToUser(userId, roleId);
        }
    }
}
